package com.ibuonline.b2b.admin.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.orm.hibernate3.HibernateCallback;

import com.dimeng.common.base.SuperDAO;
import com.ibuonline.b2b.entity.Member;
import com.ibuonline.b2b.entity.PaidGoldShop;

/**
 * 
 * @author lianglong
 * @date Jul 29, 2011
 * @time 2:59:30 PM
 * @version V 1.0 $Id: PaidGoldShopDAO.java 7100 2011-11-25 10:39:28Z fengyong $
 */
public class PaidGoldShopDAO extends SuperDAO<PaidGoldShop> {

	@SuppressWarnings("unchecked")
	public List<PaidGoldShop> pagingPaidGoldShop(final String sql, final Object[] fieldValues) {
    	return this.getJdbcTemplate().query(sql, fieldValues, new RowMapper() {
			@Override
			public Object mapRow(ResultSet rs, int i) throws SQLException {
				PaidGoldShop pgs = new PaidGoldShop();
				pgs.setCompanyId(rs.getInt("company_id"));
				pgs.setCompanyName(rs.getString("company_name"));
				pgs.setMemberAccount(rs.getString("login_name"));
				pgs.setStatus(rs.getInt("status"));
				pgs.setOperatorName(rs.getString("admin"));
				pgs.setStartDate(rs.getTimestamp("start_date"));
				pgs.setEndDate(rs.getTimestamp("end_date"));
				return pgs;
			}
		});
	}
    
    public int countRecord(String sql, Object[] params) {
    	return jdbcTemplate.queryForInt(sql, params);
    }
    
    @SuppressWarnings("unchecked")
	public boolean updatePaidGoldShop(final PaidGoldShop pgs, final String memberGrade) {
    	return (Boolean) template.execute(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException, SQLException {
				Transaction transaction = null;
				try {
					transaction = session.beginTransaction();
					final Member member = (Member) session.get(Member.class, pgs.getCompanyId());
					member.setMemberGrade(memberGrade);
					session.saveOrUpdate(member);
					session.saveOrUpdate(pgs);
					transaction.commit();
					return true;
				} catch (final Exception e) {
					if (transaction != null)
						transaction.rollback();
					return false;
				}
			}
		});
    }
    
    @SuppressWarnings("unchecked")
	public boolean updateMore(final List<PaidGoldShop> paidGoldShops) {
    	return (Boolean) template.execute(new HibernateCallback() {
			public Object doInHibernate(final Session session)
					throws HibernateException, SQLException {
				Transaction transaction = null;
				try {
					transaction = session.beginTransaction();
					for(PaidGoldShop pg : paidGoldShops) {
						session.update(pg);
					}
					transaction.commit();
					return true;
				} catch (final Exception e) {
					if (transaction != null)
						transaction.rollback();
					return false;
				}
			}
		});
    }
}

